<?php

// 修改密码
// PUT member.pwd.update

namespace app\api\resource\member\pwd;
use think\Db;
use think\Loader;
use think\Session;

class Update
{
    // 方法
    public $_method = ['PUT'];
    // 前置
    public $_pre    = ['login'];
    // 描述
    public $_description = '修改密码';
    // 参数
    public $_param  = [
        'passport' => '原密码',
        'password' => '密码',
        'confpwd'  => '确认密码',
    ];
    // 返回
    public $_return = [
        201 => '更新成功',
        400 => '原密码不正确',
        422 => '请求参数不合法',
        500 => '服务器错误',
    ];

    public function run(&$request)
    {
        $params['passport'] = $request->put('passport/s','','trim');
        $params['password'] = $request->put('password/s','','trim');
        $params['confpwd']  = $request->put('confpwd/s','','trim');

        $validate = Loader::validate('Member');
        if ( !$validate->scene('updatePwd')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $memberId = Session::get('member.id');

        $where['id']       = $memberId;
        $where['password'] = md5($params['passport']);
        $ret = Db::name('member')->where($where)->find();

        if ( is_null($ret) ) return [400,'原密码不正确'];

        $data['password'] = md5($params['password']);
        $num = Db::name('member')->where('id',$ret['id'])->update($data);

        return ($num > 0) ? [ 201,[] ] : 500;
    }
}